/**
 * 公司信息相关的自定义Hook
 *
 * 提供公司信息和联系信息的获取和管理功能
 */
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '../services/api';
import { CompanyInfo, ContactInfo } from '../types';

// 查询键常量
const QUERY_KEYS = {
  companyInfo: ['company', 'info'] as const,
  contactInfo: ['company', 'contact'] as const,
};

// 公司信息API函数
const companyApi = {
  getCompanyInfo: async (): Promise<CompanyInfo> => {
    return api.get<CompanyInfo>('/api/company/info');
  },

  getContactInfo: async (): Promise<ContactInfo> => {
    return api.get<ContactInfo>('/api/company/contact');
  },

  createCompanyInfo: async (data: Omit<CompanyInfo, 'id' | 'created_at' | 'updated_at'>): Promise<CompanyInfo> => {
    return api.post<CompanyInfo>('/api/company/info', data);
  },

  updateCompanyInfo: async (data: Partial<Omit<CompanyInfo, 'id' | 'created_at' | 'updated_at'>>): Promise<CompanyInfo> => {
    return api.put<CompanyInfo>('/api/company/info', data);
  },

  deleteCompanyInfo: async (): Promise<{ message: string }> => {
    return api.delete<{ message: string }>('/api/company/info');
  },
};

/**
 * 获取公司信息
 */
export const useCompanyInfo = () => {
  return useQuery({
    queryKey: QUERY_KEYS.companyInfo,
    queryFn: () => companyApi.getCompanyInfo(),
    staleTime: 10 * 60 * 1000, // 10分钟内数据被认为是新鲜的
    retry: false, // 如果公司信息不存在，不重试
  });
};

/**
 * 获取联系信息（公开接口，无需认证）
 */
export const useContactInfo = () => {
  return useQuery({
    queryKey: QUERY_KEYS.contactInfo,
    queryFn: () => companyApi.getContactInfo(),
    staleTime: 15 * 60 * 1000, // 15分钟内数据被认为是新鲜的
    retry: 1, // 最多重试1次
  });
};

/**
 * 创建公司信息
 */
export const useCreateCompanyInfo = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: Omit<CompanyInfo, 'id' | 'created_at' | 'updated_at'>) =>
      companyApi.createCompanyInfo(data),
    onSuccess: (newCompanyInfo) => {
      // 更新缓存
      queryClient.setQueryData(QUERY_KEYS.companyInfo, newCompanyInfo);
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.contactInfo });
    },
  });
};

/**
 * 更新公司信息
 */
export const useUpdateCompanyInfo = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: Partial<Omit<CompanyInfo, 'id' | 'created_at' | 'updated_at'>>) =>
      companyApi.updateCompanyInfo(data),
    onSuccess: (updatedCompanyInfo) => {
      // 更新缓存
      queryClient.setQueryData(QUERY_KEYS.companyInfo, updatedCompanyInfo);
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.contactInfo });
    },
  });
};

/**
 * 删除公司信息
 */
export const useDeleteCompanyInfo = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: () => companyApi.deleteCompanyInfo(),
    onSuccess: () => {
      // 清除缓存
      queryClient.removeQueries({ queryKey: QUERY_KEYS.companyInfo });
      queryClient.removeQueries({ queryKey: QUERY_KEYS.contactInfo });
    },
  });
};

/**
 * 公司信息管理的综合Hook
 */
export const useCompanyManagement = () => {
  const createMutation = useCreateCompanyInfo();
  const updateMutation = useUpdateCompanyInfo();
  const deleteMutation = useDeleteCompanyInfo();

  return {
    // 创建
    createCompanyInfo: createMutation.mutate,
    isCreating: createMutation.isPending,
    createError: createMutation.error,

    // 更新
    updateCompanyInfo: updateMutation.mutate,
    isUpdating: updateMutation.isPending,
    updateError: updateMutation.error,

    // 删除
    deleteCompanyInfo: deleteMutation.mutate,
    isDeleting: deleteMutation.isPending,
    deleteError: deleteMutation.error,

    // 重置错误状态
    resetErrors: () => {
      createMutation.reset();
      updateMutation.reset();
      deleteMutation.reset();
    },
  };
};